package top.saplf.sileny.reader.shelf

import com.github.ajalt.timberkt.Timber
import io.reactivex.Observable
import io.realm.Realm
import io.realm.RealmQuery
import io.realm.RealmResults
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * @author saplf
 */
class LocalBookLoader {
    private val realm: Realm by lazy { Realm.getDefaultInstance() }

    fun loadFirstPage(): Observable<List<LocalBook>> {
        return Observable.just(obtainData())
    }

    fun loadNextPage(localBook: LocalBook): Observable<List<LocalBook>> {
        realm.beginTransaction()
        realm.insert(localBook)
        realm.commitTransaction()
        return Observable.just(listOf(localBook))
    }

    fun loadRefreshData(): Observable<List<LocalBook>> {
        return Observable.just(obtainData())
    }

    private fun obtainData(): List<LocalBook> {
        val query: RealmQuery<LocalBook> = realm.where(LocalBook::class.java)
        return query.findAll() + emptyList()
    }

    fun close() {
        realm.close()
    }
}
